package com.aierkeji.call.b2c.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.aierkeji.call.b2c.util.AppConfig;
import com.aierkeji.call.b2c.util.GsonUtils;
import com.aierkeji.call.b2c.util.ResultMapHelper;

/**
 * cms 接口过滤器 判断token
 * 
 * @author 陈宇强
 *
 */
@WebFilter(urlPatterns = { "/cmsApi/*" })
public class CmsFilter implements Filter {
	private final Logger log = LogManager.getLogger(getClass());

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		log.info("init CmsFilter" );
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		log.info("in cmsApi filter:{},:{}", httpServletRequest.getServletPath(), httpServletRequest.getRequestURI());
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		if (!AppConfig.getProperty("cmsApiToken", "").equals(httpServletRequest.getHeader("cmsApiToken"))) {
			Map<String, Object> map = ResultMapHelper.failure("token failure");
			response.getWriter().write(GsonUtils.parseToJson(map));
			return;
		}
		chain.doFilter(httpServletRequest, httpServletResponse);

	}

}
